import json

import requests
import base64
from urllib import parse
import os
#API_KEY  SECRET_KEY    是百度云创建应用生成的  -https://console.bce.baidu.com/ai/#/ai/ocr/app/list
API_KEY = "EN3NPqyK9SeQvqAF1IZHueIC"
SECRET_KEY = "keGnM6ZvEYfq28thepFFKaUUotfzB91z"


def script_discerns(path):   #path   是文件对象
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + get_access_token()

    #id_card_side=front    front是身份证的正面   back是反面
    payload = 'id_card_side=front&image='+str(get_file_content_as_base64(path, True))
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    # print(payload)
    response = requests.request("POST", url, headers=headers, data=payload)

    # print(response.text)
    discern_dict = response.text
    discern_dict = json.loads(discern_dict)
    return discern_dict    #返回的是json


def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded
    :return: base64编码信息
    """                        #身份证图片存放的路径
    save_path = os.path.join('youzhu_api/libs/script_discern/id_care',str(path))
    # print(save_path)
    f = open(save_path, 'wb+')
    for chunk in path.chunks():
        f.write(chunk)
    f.close()
    f2 = open(save_path, "rb")
    content = base64.b64encode(f2.read()).decode("utf8")
    if urlencoded:
        content = parse.quote_plus(content)
    f2.close()
    return content


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


